<?php
namespace app\api\controller;
use app\common\controller\ApiBase;
use app\common\library\ErrorType;
use app\common\library\YuUtil;
use app\common\model\Type;
use think\db;
use think\Exception;
use app\common\library\YuDa;


/**
 * @title 个人分类管理类
 * @description 个人分类管理类
 * @package app\api\controller
 */
class Pertype extends ApiBase
{
    /**
     * @var 用户登陆的id
     */
    protected $uid;
    /**
     * @var 用户操作的typeid
     */
    protected $typeid;
    /**
     * @var array 前置操作，这里是检查各类参数所有方法名，小写
     */
    protected $beforeActionList = [
        //检查是否登录
        'checkAuth'=>['except'=>'simpleshow'],
        //检查是否有传typeid
        'checkParamsTypeId'=>['except'=>'addtypebyleveldown,simpleshow,showtypes,checkauth,istypeexistbyname,upload'],
    ];


    /**
     * @title 检查登录
     * @description 检查登录
     * @author Admin ldy
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/19  9:36
     */
    protected function checkAuth(){
        /// 如需登录，调用此方法鉴权
        /// 注解1：如果已经登录，则会获取到uid;否则会直接打印错误信息，不执行下面的代码
        /// 注解2：该方法走的是缓存，不通过数据库检查
        /// 注解3：如果没有token信息，需要调登录接口，重新获取token，并保存，token有效期暂定为30天
        /// 注解4：该类所有方法需要登录鉴权，故预先加载
        $this->uid = $this->getUidByCheck();
    }

    /**
     * @title 检查传递的typeid是否为空
     * @description 检查传递的typeid是否为空
     * @author Admin ldy
     * @param name:typeid  type:string require:1 default:1 desc:
     * @time 2018/9/26  10:55
     */
    protected function checkParamsTypeId(){
        $this->typeid = $this->getTypeIdByCheck();
    }

    /**
     * @title 展示用户的所有分类
     * @description 展示用户的所有分类？这里有待研究升级，是否有需要，分页加载？
     * @author Admin ldy
     * @url /api/Pertype/showTypes
     * @param name:token  type:string require:1 default:1 desc: 身份验证
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @time 2018/9/26  8:43
     */
    public function showTypes(){
        $uid = $this->uid;
        $checkFirstTypeRe = \app\common\library\YuUnDeleteType::checkFirstTypeByUid($uid);
        if (!$checkFirstTypeRe->getStatus()){
            $this->err($checkFirstTypeRe->getMsg());
        }
        $typearr = Db::table('scj_type')->where('uid',$this->uid)->select();
        if ($typearr){
            $this->success('获取数据成功！',$typearr,200);
        }else{
            $this->err(ErrorType::GET_DATA_FAILED);
        }
    }

    /**
     * @title 某个类型是否有下级
     * @description 某个类型是否有下级，在调用删除deleteTypeMore多个类型的时候，可以先查询知道是否有下级
     * @author Admin ldy
     * @url /api/pertype/isTypeHasSon
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     * @time 2018/9/26  10:43
     */
    public function  isTypeHasSon(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $con = array(
            'uid'=>$uid,
            'pid'=>$typeid,
        );
        try {
            $typearr = Db::table('scj_type')->where($con)->select();
            if ($typearr) {
                $this->success('该用户的这个类型有下级！', $typearr,200);
            } else {
                $this->error('该用户的这个类型无下级。', array('uid'=>$uid),1003);
            }
        }catch (Exception $e){
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }
    }

    /**
     * @title 某个类型是否有父级
     * @description 某个类型是否有父级
     * @author Admin ldy
     * @url /api/pertype/isTypeHasPersent
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  10:43
     */
    public function isTypeHasPersent(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $re = YuDa::getTypeStringById($typeid,$uid);
        if ($re->getStatus()){
            $this->success('该用户的这个类型有父级！', array('str'=>$re->getData()),200);
        }else{
            $this->err($re->getMsg());
        }


    }

    /**
     * @title 某个类型是否已经存在(根据id)
     * @description 某个类型是否已经存在(依据id)
     * @author Admin ldy
     * @url /api/pertype/isTypeExistById
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  11:03
     */
    public function isTypeExistById(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $con = array(
            'uid'=>$uid,
            'id'=>$typeid,
        );
        try {
            $type = Db::table('scj_type')->where($con)->find();
            if ($type) {
                $this->success('该用户的这个类型存在！', array('type'=>$type),200);
            } else {
                $this->error('该用户的这个类型不存在', array('uid'=>$uid),1003);
            }
        }catch (Exception $e){
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }
    }

    /**
     * @title 某个类型是否已经存在（依据名字）
     * @description 某个类型是否已经存在（依据名字）
     * @author Admin ldy
     * @url /api/pertype/isTypeExistByName
     * @param name:name  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  11:03
     */
    public function isTypeExistByName(){
        $name = $this->request->param('name');
        $this->checkEmptyParams($name);

        $uid = $this->uid;
        $con = array(
            'uid'=>$uid,
            'name'=>$name,
        );
        try {
            $type = Db::table('scj_type')->where($con)->find();
            if ($type) {
                $this->success('该用户的这个类型存在！', array('type'=>$type),200);
            } else {
                $this->error('该用户的这个类型不存在', array('uid'=>$uid),1003);
            }
        }catch (Exception $e){
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }
    }

    /**
     * @title 增加类型（下级）
     * @description 增加类型（下级）
     * @author Admin ldy
     * @url /api/pertype/addTypeByLevelDown
     * @param name:typeid  type:string require:1 default:1 desc:选中的类型
     * @param name:token  type:string require:1 default:1 desc:身份验证
     * @param name:name  type:string require:1 default:1 desc:新增下级的名字
     * @time 2018/9/26  10:37
     */
    public function addTypeByLevelDown(){
//        $typeid = $this->typeid;//不通过公共的检查之后，不能这样获取id
        $typeid = $this->request->param('typeid');
        if (empty($typeid)){
            $typeid = 0;
        }
        $uid = $this->uid;
        $name = $this->request->param('name');
        $this->checkEmptyParams($name);
        try{
            $con = array(
              'name'=>$name,
              'pid' =>$typeid,
            );
            $isTypeExist =Db::table('scj_type')->where($con)->find();
            if ($isTypeExist){
                //同一目录下面，应该命名不同
                $this->err(ErrorType::DATA_EXIST);
            }
                //增加的是下级，所以，当前id变成新增加的类型的父级id
            $pid = $typeid;
            $typeModel = new Type();
            $typeModel->pid = $pid;
            $typeModel->uid = $uid;
            $typeModel->name = $name;
            $re = $typeModel->save();
            if ($re){
                rewardNormal($uid,'新增【分类】成功！');
                $this->success('新增成功！',$typeModel,200);
            }else{
                $this->err(ErrorType::ADD_DATA_FAILED);
            }
        }catch (Exception $e){
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }

    }

    /**
     * @title 增加类型（同级）
     * @description 增加类型（同级）
     * @author Admin ldy
     * @url /api/pertype/addTypeByLevelLeft
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:name  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  10:37
     */
    public function  addTypeByLevelLeft(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $name = $this->request->param('name');
        $this->checkEmptyParams($name);
        try{
            $con = array(
                'name'=>$name,
            );
            $isTypeExist =Db::table('scj_type')->where($con)->find();
            if ($isTypeExist){
                $this->err(ErrorType::DATA_EXIST);
            }
            //增加的是同级，需要获取当前类型的父id
            $nowtype = \app\common\model\Type::getById($typeid);
            if (!$nowtype){
                $this->err(ErrorType::DATA_EXCEPTION);
            }
            //增加的是同级，所以，当前pid变成新增加的类型的父级id
            $pid = $nowtype['pid'];

            $typeModel = new Type();
            $typeModel->pid = $pid;
            $typeModel->uid = $uid;
            $typeModel->name = $name;
            $re = $typeModel->save();
            if ($re){
                $this->success('新增成功！',$typeModel,200);
            }else{
                $this->err(ErrorType::ADD_DATA_FAILED);
            }
        }catch (Exception $e){
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }
    }

    /**
     * @title 删除一条类型(待开发)
     * @description 删除一条类型
     * @author Admin ldy
     * @url /api/pertype/deleteTypeOne
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  10:40
     */
    public function deleteTypeOne(){

    }

    /**
     * @title 删除一条类型(有下级的情况)(待开发)
     * @description 删除一条类型(有下级的情况)
     * @author Admin ldy
     * @url /api/pertype/deleteTypeOne
     * @param name:typeid  type:string require:1 default:1 desc:
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/26  10:40
     */
    public function deleteTypeMore(){

    }


    /**
     * @title 删除一条类型(自动区分是否有下级)
     * @description 删除一条类型(自动区分是否有下级)
     * @author Admin ldy
     * @url /api/pertype/deleteTypeOneOrMore
     * @param name:typeid  type:string require:1 default:1 desc:id
     * @param name:token  type:string require:1 default:1 desc:身份验证
     * @time 2018/9/26  10:40
     */
    public function deleteTypeOneOrMore(){
        $typeid = $this->typeid;
        $uid = $this->uid;

        //检查是否是初始的数据，如果是的话，就不允许删除！
        $undeleteTypeDataRe =\app\common\library\YuUnDeleteType::getUserUnDeleteType($uid);
        if ($undeleteTypeDataRe->getStatus()){
            $arr = $undeleteTypeDataRe->getData();
            if (in_array($typeid,$arr)){
                $this->err(ErrorType::CAN_NOT_DELETE_ORIGINAL_DATA);
            }
        }

        // 启动事务
        Db::startTrans();
        try {
            $typearr = Db::table('scj_type')->where('uid', $uid)->select();
//        //pid是指一级目录下面的二级的所有树，例如pid = 1的时候，展示所有江苏省下面的市级、区、县、镇、街道
            //获取某条类型的所有子级
            $array = YuUtil::getTree($typearr, $typeid, 0);
            if ($array){
                $list=array();
                foreach ($array as $key=>$item) {
                    $list[$key] = $item['id'];
                }
                $count = count($list);
                $list[$count] = $typeid;
                //如果有，就逐条删除
               $re = Db::table('scj_type')->delete($list);

            }else{
                //如果没有，就只删除一条数据
                $re = Db::table('scj_type')->delete($typeid);
            }

            // 提交事务
            Db::commit();
            if ($re){
                rewardNormal($uid,'删除【分类】成功！');
                $this->success('删除成功！',$re,200);
            }else{
                // 回滚事务
                Db::rollback();
                $this->err(ErrorType::ACTION_FAILED);
            }
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            $this->err(ErrorType::GET_DATA_FAILED,$e->getTraceAsString());
        }
    }


    /**
     * @title 更新一条类型
     * @description 更新一条类型,修改了父亲id，就可以移动位置
     * @author Admin ldy
     * @url /api/pertype/updateType
     * @param name:typeid  type:string require:1 default:1 desc:类型自身的id
     * @param name:token  type:string require:1 default:1 desc:身份验证
     * @param name:name  type:string require:1 default:1 desc:类型的名字
     * @param name:pid  type:string require:1 default:1 desc:类型的父亲id
     * @time 2018/9/26  11:11
     */
    public function updateType(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $name = $this->request->param('name');
        $pid = $this->request->param('pid');
        $this->checkEmptyParams($name);
        $this->checkEmptyParams($pid);
        $nowtype = \app\common\model\Type::getById($typeid);
        if ($nowtype){
            $nowtype->name = $name;
            $nowtype->pid = $pid;
            $nowtype->uid = $uid;
            $re = $nowtype->save();
            if ($re){
                rewardNormal($uid,'修改【分类】成功！');
                $this->success('修改成功！',$re,200);
            }else{
                $this->err(ErrorType::ACTION_FAILED);
            }
        }else{
            $this->err(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title 移动一个目录到另一个目录下面
     * @description 更新一条类型,修改了父亲id，就可以移动位置
     * @author Admin ldy
     * @url /api/pertype/moveType
     * @param name:typeid  type:string require:1 default:1 desc:类型自身的id
     * @param name:token  type:string require:1 default:1 desc:身份验证
     * @param name:pid  type:string require:1 default:1 desc:类型的父亲id
     * @time 2018/9/26  11:11
     */
    public function moveType(){
        $typeid = $this->typeid;
        $uid = $this->uid;
        $pid = $this->request->param('pid');
        $this->checkEmptyParams($pid);
        $nowtype = \app\common\model\Type::getById($typeid);
        if ($nowtype){
            $nowtype->pid = $pid;
            $nowtype->uid = $uid;
            $re = $nowtype->save();
            if ($re){
                rewardNormal($uid,'移动【分类】成功！');
                $this->success('修改成功！',$re,200);
            }else{
                $this->err(ErrorType::ACTION_FAILED);
            }
        }else{
            $this->err(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title 重命名类型
     * @description 重命名类型
     * @author Admin ldy
     * @url /api/pertype/renameType
     * @param name:typeid  type:string require:1 default:1 desc:类型自身的id
     * @param name:token  type:string require:1 default:1 desc:身份验证
     * @param name:name  type:string require:1 default:1 desc:类型的名字
     * @time 2018/9/26  11:11
     */
    public function renameType(){
        $typeid = $this->typeid;
        $uid=$this->uid;
        $name = $this->request->param('name');
        $this->checkEmptyParams($name);
        $this->checkEmptyParams($typeid);
        $nowtype = \app\common\model\Type::getById($typeid);
        if ($nowtype){
            $nowtype->name = $name;
            $re = $nowtype->save();
            if ($re){
                rewardNormal($uid,'重命名【分类】成功！');
                $this->success('修改成功！',$nowtype,200);
            }else{
                $this->err(ErrorType::ACTION_FAILED);
            }
        }else{
            $this->err(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title 上传数据
     * @description 上传数据
     * @author Admin ldy
     * @url /api/pertype/upload
     * @param name:token  type:string require:1 default:1 desc:
     * @param name:d  type:string require:1 default:1 desc:用户的json数据
     * @time 2018/11/5  14:51
     */
    public function upload(){
        $jsonstring = $this->request->param('d');
        $this->checkEmptyParams($jsonstring);
        $re = \app\common\library\YuActivity::uploadUserData($this->uid,$jsonstring);
        if ($re->getStatus()){
            $this->success($re->getMsg(),$re->getData());
        }else{
            $this->err(ErrorType::ACTION_FAILED,$re->getData());
        }
    }

    /**
     * @title 简单展示页面
     * @description 简单展示页面,这个仅仅用于第一版展示，
     * @author Admin ldy
     * @url /api/pertype/simpleShow
     * @param name:id  type:string require:1 default:1 desc:用户id
     * @time 2018/9/26  17:34
     */
    public function simpleShow(){
        $uid = $this->request->param('id');
        if (empty($uid)){
            $uid = 14;
        }
        try {
            $typearr = Db::table('scj_type')->where('uid', $uid)->select();
//        //pid是指一级目录下面的二级的所有树，例如pid = 1的时候，展示所有江苏省下面的市级、区、县、镇、街道
            $array = YuUtil::getTree($typearr, 0, 0);

            foreach ($array as $item) {
                echo str_repeat('-- ', $item['level']), $item['name'] . '(' . $item['level'] . ')<br />';
            }
        }catch (Exception $e){
            $this->err(ErrorType::DATA_EXCEPTION);
        }
        //调试删除子级数据
//        var_dump($array);
//        echo '<br>';

//        $list=array();
//        foreach ($array as $key=>$item) {
//            $list[$key] = $item['id'];
////            echo str_repeat('-- ', $item['level']), $item['name'].'('.$item['level'].')<br />';
//        }
//        var_dump($list);
//        echo '<br>';

            ///错误类的设计实现
//        $erType =new \app\common\library\ErrorType(ErrorType::CUSTOM,'sdfsdfsdf','456');
//        $data = $erType->getMsg();
//        $data = $erType->getCode();
//        $data = $erType->getType();
//        $data = $erType->getObjectString();
//        var_dump($data);
    }


}
